package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.base.MVPBaseActivity;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.presenter.SettingPresenter;
import com.jianyun.jyzs.utils.Const;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.PathUtil;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.ISettingView;
import com.jianyun.jyzs.widget.ListItemTextView;
import com.jianyun.jyzs.widget.PromptPopupDialog;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 设置界面
 * Created by yangshijun on 2018/5/28.
 */

public class SettingActivity extends MVPBaseActivity<ISettingView, SettingPresenter> implements ISettingView {


    @BindView(R.id.liv_setting_clear_cache)
    ListItemTextView livSettingClearCache;
    @BindView(R.id.tv_exit)
    TextView tvExit;
    @BindView(R.id.tv_about)
    ListItemTextView tvAbout;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rce_activity_setting);
        ButterKnife.bind(this);
    }

    @NonNull
    @Override
    public SettingPresenter createPresenter() {
        return new SettingPresenter();
    }


    @OnClick({R.id.tv_about,
            R.id.liv_setting_clear_cache, R.id.tv_exit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_about:
                startActivity(new Intent(this, AboutJyzsActivity.class));
                break;
            case R.id.liv_setting_clear_cache:
                PromptPopupDialog dialog = PromptPopupDialog.newInstance(this, "", getString(R.string.rce_clear_cache_prompt));
                dialog.setPromptButtonClickedListener(new PromptPopupDialog.OnPromptButtonClickedListener() {
                    @Override
                    public void onPositiveButtonClicked() {
                        File file = new File(Environment.getExternalStorageDirectory().getPath() + getPackageName());
                        deleteFile(file);
                        String paths= PathUtil.pathPrefix;
                        //删除文件夹下面所有的文件
                        boolean b = deleteAllFile(paths);
                        Log.i("test","文件："+b);
                        Toast.makeText(SettingActivity.this, getString(R.string.rce_clear_cache_success), Toast.LENGTH_SHORT).show();
                    }
                });
                dialog.show();
                break;
            case R.id.tv_exit:
                //退出登录
                dialog = PromptPopupDialog.newInstance(this, "", getString(R.string.rce_logout_prompt));
                dialog.setPromptButtonClickedListener(new PromptPopupDialog.OnPromptButtonClickedListener() {
                    @Override
                    public void onPositiveButtonClicked() {
                        cancelID();
                        LoginCache.getInstance().setLoginOut();
                        Intent loginActivityIntent = new Intent();
                        RetrofitHelper.clear();
                        loginActivityIntent.putExtra(Const.LOGOUT, true);
                        loginActivityIntent.setClass(SettingActivity.this, LoginActivity.class);
                        loginActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(loginActivityIntent);


                        finish();
                        //清除代办个数
                        //SPUtils.remove(SettingActivity.this,"workflow_count");
                    }
                });
                dialog.show();
                break;
        }
    }

    /**
     * 取消极光设备ID
     */
    public void cancelID(){
        String userId = LoginCache.getInstance().getUserInfo().getUserId();
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        if (!rid.isEmpty()) {
            Api api = RetrofitHelper.builderCeshiHttp().create(Api.class);
            //Log.i("test","userid:"+userId+"\nrid:"+rid);
            api.cancelId("CancleRegistration_id", userId, rid,
                    "jyzs","Android","1.0.2")
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<Object>() {
                        @Override
                        public void onError(Throwable e) {
                            Log.i("test","取消设备ID失败");
                            e.printStackTrace();
                        }

                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onNext(Object o) {
                            String s = new Gson().toJson(o);
                            Log.i("test", "取消RegistrationId：" + s.toString());
                        }
                    });
        }
    }


    @Override
    public void onCreateActionBar(ActionBar actionBar) {
        final View actionBarView = actionBar.setActionBar(R.layout.rce_actionbar_option_text);
        ImageButton backImgBtn = (ImageButton) actionBarView.findViewById(R.id.imgbtn_custom_nav_back);
        backImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView titleTextView = (TextView) actionBarView.findViewById(R.id.tv_custom_nav_title);
        titleTextView.setText(R.string.rce_me_setting);
    }

    /**
     * 删除文件夹下面的所有的文件
     * @param path
     */
    private boolean deleteAllFile(String path) {

        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                deleteAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public  void delFolder(String folderPath) {
        try {
            deleteAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void deleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                deleteFile(f);
            }
            file.delete();
        }
    }
}
